package com.jwaoo.chat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.dx.as.JWCache;
import com.dx.as.common.log.LogUtil;
import com.google.gson.Gson;
import com.jwaoo.chat.activity.P2PMessageActivity;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.fragment.session.bean.SessionBean;
import com.jwaoo.chat.session.Extras;
import com.jwaoo.chat.session.avchat.AVChatActivity;
import com.jwaoo.chat.session.avchat.AVChatType;
import com.jwaoo.im.ImClient;
import com.jwaoo.protobuf.ImBase;
import com.jwaoo.protobuf.ImCommand;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.jwaoo.chat.data.db.MessageHandler.SAVE_MESSAGE;
import static com.jwaoo.chat.data.db.MessageHandler.SAVE_SESSION;
import static com.jwaoo.chat.data.db.MessageHandler.UPDATE_MESSAGE;

/**
 * Created by jwaoo on 2017/7/4.
 */

public class IMessageClient extends ImClient{
    private Gson gson = new Gson();
    private int  id;
    private Map<Integer,Message> messageMap = new HashMap<>();
    public IMessageClient(int id) {
        super();
        this.id = id;
    }

    @Override
    public void onConnected() {
        super.onConnected();
        try{
//            Log.e("IMessageClient","onConnected");
            this.doLogin(id, ImBase.ImClientType.IM_CLIENT_ANDROID);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public boolean sendMessage(Message message,String json){
        messageMap.put(message.get_id(),message);
        return sendMessage(message.get_id(), message.getFriend(),11,json);
    }

    @Override
    public void onDisconnected() {
//        LogUtil.e("IMessageClient","onDisconnected");
        super.onDisconnected();
    }

    @Override
    public void onLoginSuccess() {
        super.onLoginSuccess();
        LogUtil.e("IMessageClient","loginSuccess");
    }

    @Override
    public void onLoginFailed() {
        super.onLoginFailed();
        LogUtil.e("IMessageClient","loginFailed");
    }

    @Override
    public void onSendMessageSuccess(int msgId, int remoteId, int sendTime) {
        super.onSendMessageSuccess(msgId, remoteId, sendTime);
        sendBroad(msgId,ChatConstants.success);
    }

    public void sendBroad(int msgId ,int state){
        Message message = messageMap.get(msgId);
        message.setState(state);
        MessageHandler.getInstace(JWCache.getContext()).handlerMessages(UPDATE_MESSAGE,message);
        sendMessageBroad(message);
    }

    @Override
    public void onSendMessageFailed(int msgId,int error) {
        super.onSendMessageFailed(msgId,error);
        sendBroad(msgId,ChatConstants.fail);
    }


    @Override
    public boolean onOfflineMessageReceived(ImCommand.ImMessageInfo message) {
        return onMessageReceived(message);
    }

    @Override
    public void onGetServerFailed() {
        super.onGetServerFailed();
        //服务器连接异常
    }

    @Override
    public boolean onOnlineMessageReceived(ImCommand.ImMessageInfo info) {
        return onMessageReceived(info);
    }

    private boolean onMessageReceived(ImCommand.ImMessageInfo info){
        try{
            int friend = info.getUserId();
            String jsonStr = new String(info.getMsgData().toByteArray());
            Log.e("jsonStr",jsonStr);
            Message message = gson.fromJson(jsonStr,Message.class);
            message.setFriend(friend);
            handlerMessage(message);
            handlerSession(message);

            if (message.getMsgtype() == AVChatType.VIDEO.getValue() || message.getMsgtype() == AVChatType.AUDIO.getValue()){
                if (ChatHelpter.isCurrentActivity(AVChatActivity.class)) return true;
                AVChatActivity.launch(ChatHelpter.getContext(),message.getFriend(),message.getMsgtype(),message.getMsg());
            }else{
                sendNotification(message.getFriend());
            }

        }catch (Exception ex){
            ex.printStackTrace();
            return false;
        }
        return true;
    }


    private void handlerSession(Message message){
        SessionBean sessionBean = new SessionBean();
        sessionBean.setMsgtype(message.getMsgtype());
        sessionBean.setMsg(message.getMsg());
        sessionBean.setSessionType(message.getSessionType());
        if (ChatHelpter.currentSessionId == message.getFriend()) sessionBean.setCount(0);
        else sessionBean.setCount(1);
        sessionBean.setFriend(message.getFriend());
        List<SessionBean> list = new ArrayList<>();
        list.add(sessionBean);
        MessageHandler.getInstace(JWCache.getContext()).handlerMessages(SAVE_SESSION,list);
        sendSessionBroad();
    }

    private void handlerMessage(Message message){
        int _id = (int)System.currentTimeMillis();
        message.set_id(_id);
        message.setDirect(ChatConstants.In);
        message.setState(ChatConstants.success);
        message.setIsRead(ChatConstants.unread);
        message.setAttachState(ChatConstants.transferred);
        MessageHandler.getInstace(JWCache.getContext()).handlerMessages(SAVE_MESSAGE,message);
        sendMessageBroad(message);
        messageMap.put(_id,message);
    }

    private void sendSessionBroad(){
        //发送信息
        Intent intentSession = new Intent();
        intentSession.setAction(ChatConstants.ACTION);
        JWCache.getContext().sendBroadcast(intentSession);
    }

    private void sendMessageBroad(Message message){
        Intent intentMessage = new Intent();
        intentMessage.setAction(ChatConstants.ACTION_MESSAGE);
        intentMessage.putExtra(Extras.EXTRA_MESSAGE,message);
        JWCache.getContext().sendBroadcast(intentMessage);
    }


        private void sendNotification(int account) {
            Bitmap icon = BitmapFactory.decodeResource(ChatHelpter.getContext().getResources(), R.drawable.nim_actionbar_dark_logo_icon);

            Intent intent = new Intent(ChatHelpter.getContext(), P2PMessageActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

            Bundle bundle = new Bundle();
            bundle.putInt(Extras.EXTRA_ACCOUNT, account);
            intent.putExtras(bundle);

            PendingIntent pendingIntent = PendingIntent.getActivity(ChatHelpter.getContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ChatHelpter.getContext())
                    .setContentTitle("消息提示")
                    .setContentText("您有一条新信息！")
                    .setAutoCancel(true)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    //.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.win))
                    .setContentIntent(pendingIntent)
                    .setContentInfo("Hello")
                    .setLargeIcon(icon)
                    .setColor(Color.RED)
                    .setLights(Color.RED, 1000, 300)
                    .setDefaults(Notification.DEFAULT_VIBRATE)
                    .setTicker("您有一条新信息！")
                    .setSmallIcon(R.drawable.nim_actionbar_nest_dark_logo);

            notificationBuilder.setStyle(
                    new NotificationCompat.BigPictureStyle().bigPicture(icon).setSummaryText("您有一条新消息！")
            );

            NotificationManager notificationManager = (NotificationManager) ChatHelpter.getContext().getSystemService(Context.NOTIFICATION_SERVICE);


            notificationManager.notify(0, notificationBuilder.build());
        }
}
